# dao/redis_connect.py
"""
连接 redis
"""

import os
from typing import Optional

import redis
from redis import ConnectionPool, Redis
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# Redis配置
REDIS_HOST = os.getenv("REDIS_HOST")
REDIS_PORT = int(os.getenv("REDIS_PORT"))
REDIS_DB = int(os.getenv("REDIS_DB"))
REDIS_PASSWORD = os.getenv("REDIS_PASSWORD")  # 设置默认密码

# print(f"Debug - Redis配置: HOST={REDIS_HOST}, PORT={REDIS_PORT}, DB={REDIS_DB}, PASSWORD={REDIS_PASSWORD}")  # 临时调试信息

# 创建Redis连接池
redis_pool = ConnectionPool(
    host=REDIS_HOST,
    port=REDIS_PORT,
    db=REDIS_DB,
    password=REDIS_PASSWORD,
    decode_responses=True,  # 自动将响应解码为字符串
    max_connections=100,  # 连接池最大连接数
    socket_timeout=5,  # 套接字超时时间
)


class RedisClient:
    _instance: Optional[Redis] = None

    @classmethod
    def get_client(cls) -> Redis:
        """
        获取Redis客户端实例（单例模式）
        如果连接失败会抛出异常
        """
        if cls._instance is None:
            try:
                cls._instance = Redis(connection_pool=redis_pool)
                # 测试连接
                cls._instance.ping()
                print("Redis连接成功!")
            except redis.exceptions.AuthenticationError as e:
                print(f"Redis认证失败: {e}")
                raise
            except Exception as e:
                print(f"Redis连接错误: {e}")
                raise
        return cls._instance

    @classmethod
    def close(cls):
        """
        关闭Redis连接
        """
        if cls._instance is not None:
            cls._instance.close()
            cls._instance = None

    @classmethod
    def check_connection(cls) -> bool:
        """
        检查Redis连接是否正常
        如果连接失败会抛出异常
        """
        try:
            client = cls.get_client()
            client.ping()
            return True
        except Exception as e:
            raise Exception(f"Redis连接检查失败: {str(e)}")

# 使用示例
# redis_client = RedisClient.get_client()
